package com.moonhill.bt;

public class BTUtil {

	public static byte[] int2Bytes(int value, int len) {
		byte[] bytes = new byte[len];
		for (int i = len - 1; i >= 0; i--) {
			bytes[i] = (byte) ((value >> (8 * (len - 1 - i))) & 0xff);
		}
		return bytes;
	}

	public static void int2Bytes(int value, int len, byte[] target, int offset) {
		for (int i = len - 1; i >= 0; i--) {
			target[offset + i] = (byte) ((value >> (8 * (len - 1 - i))) & 0xff);
		}
	}

	public static int bytes2Int(byte[] bytes) {
		return bytes2Int(bytes, 0, bytes.length);
	}

	public static int bytes2Int(byte[] bytes, int offset, int len) {
		int value = 0;
		for (int i = len - 1; i >= 0; i--) {
			int b = bytes[offset + i] & 0xff;
			value = (b << (8 * (len - 1 - i))) | value;
		}
		return value;
	}

	public static final byte[] hexStrToBytes(String s) {
		byte[] bytes;

		bytes = new byte[s.length() / 2];

		for (int i = 0; i < bytes.length; i++) {
			bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),
					16);
		}

		return bytes;
	}

	public final static String byteArrayToHexString(byte in[]) {
		byte ch = 0x00;
		int i = 0;
		if (in == null || in.length <= 0)
			return null;
		String pseudo[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
				"A", "B", "C", "D", "E", "F" };
		StringBuffer out = new StringBuffer(in.length * 2);
		while (i < in.length) {
			ch = (byte) (in[i] & 0xF0); // Strip off high nibble
			ch = (byte) (ch >>> 4);
			// shift the bits down
			ch = (byte) (ch & 0x0F);
			// must do this is high order bit is on!
			out.append(pseudo[(int) ch]); // convert the nibble to a String
			// Character
			ch = (byte) (in[i] & 0x0F); // Strip off low nibble
			out.append(pseudo[(int) ch]); // convert the nibble to a String
			// Character
			i++;

		}
		String rslt = new String(out);
		return rslt;

	}
}
